package top.riske.animalhazardassessment.account.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import top.riske.animalhazardassessment.account.service.AccountService;
import top.riske.animalhazardassessment.common.entity.Account;
import top.riske.animalhazardassessment.common.enums.RoleEnum;
import top.riske.animalhazardassessment.common.http.exception.BusinessException;
import top.riske.animalhazardassessment.common.mapper.AccountMapper;
import top.riske.animalhazardassessment.common.utils.JWTUtils;

/**
 * 账号服务
 */
@Slf4j
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Resource
    private AccountMapper accountMapper;


    @Override
    public Account login(String username, String password, HttpServletResponse response) {
        Account account = accountMapper.selectOne(new QueryWrapper<Account>().lambda().eq(Account::getUsername, username));
        if(account == null){
            throw new BusinessException("用户名不存在");
        }
        // 判断密码是否正确
        if(!DigestUtil.sha256Hex(password).equals(account.getPassword())){
            throw new BusinessException("密码错误");
        }
        // 判断账号权限
        RoleEnum role = RoleEnum.getRoleEnumByCode(account.getRole());
        if(role == null){
            throw new BusinessException("未知的用户权限");
        }
        // 生成token
        String token = JWTUtils.createToken(account.getId(), role);
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        return account;
    }

    @Override
    public Account register(String username, String password, HttpServletResponse response) {
        // 加密密码
        password = DigestUtil.sha256Hex(password);

        Account account = new Account(username, password);

        try{
            int res = accountMapper.insert(account);
            if(res < 1){
                throw new BusinessException(HttpStatus.INTERNAL_SERVER_ERROR,"数据库错误");
            }
        }catch (DuplicateKeyException e){
            throw new BusinessException("用户名已存在");
        }

        // 注册成功后，生成token，避免再一次登录
        // 生成token
        String token = JWTUtils.createToken(account.getId(), RoleEnum.USER);
        response.setHeader("Authorization", token);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return account;
    }


}
